import {
  ForwardedRef,
  forwardRef,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
} from "react";
import { ComponentBaseProps } from "../../common-component/CommonTypes";
import { Tooltip } from "tdesign-react";
import { IotDeviceData } from "_common/DataType";
import { ViewerState } from "components";

export interface IotTempSingleComponentStyle {
  color?: string;
  fontSize?: number;
  fontWeight?: number;
  fontFamily?: string;
  alignItems?: string;
  justifyContent?: string;
  bordered?: string;
  borderColor?: string;
  borderRadius?: number;
  backgroundColor?: string;
  showUnit?: string; // 是否显示单位
}

export interface DeviceProps {
  terminalId: string;
  deviceCode: string;
  position?: string;
}

export interface IotTempSingleComponentProps extends ComponentBaseProps {
  style?: IotTempSingleComponentStyle;
  device?: DeviceProps;
  standardStore?: any;
}

export interface IotTempSingleComponentRef {
  updateConfig: (newConfig: IotTempSingleComponentProps) => void;
  setEventHandler: (eventMap: Record<string, Function>) => void;
  setPointClick?: (func: Function) => void;
  updateIotData?: (data: IotDeviceData) => void;
}

export const IotTempSingleComponent = forwardRef(
  (
    props: IotTempSingleComponentProps,
    ref: ForwardedRef<IotTempSingleComponentRef>
  ) => {
    const [config, setConfig] = useState<IotTempSingleComponentProps>({
      ...props,
    });
    const { style, device } = config;
    const eventHandlerMap = useRef<Record<string, Function>>({});

    // 标准数据：value1: status  0：正常，1：预警，2：报警，3：故障，4：离线
    const [standardData, setStandardData] = useState<IotDeviceData>();
    // 是否报警
    const [state, setState] = useState<number>(0);
    useImperativeHandle(ref, () => ({
      updateConfig: (newConfig) => setConfig({ ...newConfig }),
      setEventHandler: (eventMap) => (eventHandlerMap.current = eventMap),
      updateIotData: (data) => {
        if (data.deviceCode == device?.deviceCode) {
          setStandardData(data);
          setState(data.status ?? 0);
        }
      },
    }));

    // 是否报警了
    const alarm = useMemo(() => {
      return state == 1 || state == 2;
    }, [state]);

    // 是否离线了
    const offline = useMemo(() => {
      return state == 4;
    }, [state]);

    const tooltip = useMemo(() => {
      if (!device?.deviceCode)
        return <span className="text-red-500">未绑定设备</span>;
      return (
        <div className="flex flex-col items-center">
          <span>
            {!device?.position
              ? `${device?.deviceCode}`
              : `${device?.deviceCode}-${device?.position}`}
          </span>
          {alarm && <span className="text-red-500">温度报警</span>}
          {offline && <span className="text-red-500">设备离线</span>}
        </div>
      );
    }, [device, device?.deviceCode, device?.position, alarm, offline]);

    return (
      <div
        className="flex flex-row justify-around h-full cursor-pointer"
        style={{
          border: `${style?.bordered}px solid ${style?.borderColor}`,
          borderRadius: style?.borderRadius,
          backgroundColor: style?.backgroundColor,
          cursor: "pointer",
        }}
        onClick={() => {
          ViewerState.handleClick(device?.deviceCode);
        }}
      >
        <Tooltip content={tooltip}>
          <div className="left-img text-center flex flex-row items-center relative">
            {alarm && (
              <div className=" absolute" style={{ right: -10, top: -5 }}>
                <span className="relative flex h-3 w-3">
                  <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-400 opacity-75"></span>
                  <span className="relative inline-flex rounded-full h-3 w-3 bg-red-500"></span>
                </span>
              </div>
            )}
            <span
              className="text-cyan-500"
              style={{
                color: offline ? "#898989" : style?.color,
                fontSize: style?.fontSize,
                fontWeight: style?.fontWeight,
              }}
            >
              {standardData?.value1?.toFixed(1) ?? "--"}{" "}
              {style?.showUnit == "1" && "℃"}
            </span>
          </div>
        </Tooltip>
      </div>
    );
  }
);

export default IotTempSingleComponent;
